const mysql = require('mysql')
const chalk = require('chalk')
const config = require('../config')
const logger = require('./logger')

const connect = mysql.createPool(config.db)
const debug = new logger.Logger('SQL', 'debug')

function exec (sql, args) {
    return new Promise((resolve, reject) => {
        if (!config.isPrd()) {
            sql = mysql.format(sql, args)
            args = []
        }

        const start = Date.now()
        connect.query(sql, args, (err, result) => {
            if (!config.isPrd()) {
                debug.log(sql, `${chalk.gray('-')} ${chalk.cyan((Date.now() - start) / 1000)} ms`)
            }

            if (err) return reject(err)
            resolve(result)
        })
    })
}

module.exports = {
    /**
     * 执行查询
     * @param {string} sql
     * @param {any[]} args
     * @returns {Promise<object[]>}
     * **/
    findAll (sql, args) {
        return exec(sql, args)
    },

    /**
     * 执行查询，但仅返回第一个结果
     * @param {string} sql
     * @param {any[]} args
     * @returns {Promise<object>}
     * **/
    async findOne (sql, args) {
        const list = await exec(sql, args)
        return list[0] || null
    },

    /**
     * 执行sql
     * @param {string} sql
     * @param {any[]} args
     * @returns {Promise<{affectedRows: number; insertId: number; changedRows: number;}>}
     * **/
    exec (sql, args) {
        return exec(sql, args)
    }
}
